package com.rcloud.server.sealtalk.util;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Random;

@Slf4j
@Component
public class WebSocketClient {
    /**
     * 用户加入聊天室内的功能
     *
     * @param nickname
     * @return
     */
    public MyWebSocketClient joinWebSocket(String nickname) {
        Random random = new Random();
        String message;
        try {
            //实例WebSocketClient对象，并连接到WebSocket服务端
            // ws://" + window.location.hostname + ":8002/ws
            MyWebSocketClient client = new MyWebSocketClient(new URI("ws://114.117.247.50:8002/"));
            client.connect();
            //等待服务端响应
            while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                log.info("连接中···请稍后");
                Thread.sleep(random.nextInt(9999));
            }
            //向WebSocket服务端发送数据
            client.send("[LOGIN][" + new Date().getTime() + "][" + nickname + "]");
            //等待WebSocket服务端响应
            while ((message = client.getExcptMessage()) == null) {
                log.info("服务忙等待...");
                Thread.sleep(random.nextInt(9999));
            }
            //打印服务端返回的数据
            log.info("成功获取数据：" + message);
            return client;
            //关闭连接
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

}
